/** @format */

import  dayjs from 'dayjs'
import { uniq } from 'lodash'
import { getToday } from './getToday'
import { formatDate } from './date'

const isLeapYear = (year: number) => (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0
const oneDayTime = 24 * 3600 * 1000

// 获取最大连续签到天数
export const getMaxContinusSignDays = (signInfoList: ISignInfoAggregate[]): number => {
  const minYear = Math.min.apply(
    null,
    signInfoList.map(v => +v.y)
  )
  const list: number[] = signInfoList
    .map(v => {
      const gap = (isLeapYear ? 366 : 365) * (v.y - minYear)
      return gap + v.d
    })
    .sort((a, b) => a - b)

  if (list.length === 0) return 0
  let m = uniq(list.sort((a, b) => a - b))
  let max = 0
  for (let i = 0; i < m.length; i++) {
    let idx = 0
    while (m[i + 1] - m[i] === 1) {
      idx++
      i++
      max = Math.max(idx, max)
    }
  }
  return max + 1
}

// 获取某天是否签到
export const getSignedByDay = (signInfoList: ISignInfoAggregate[], day = getToday()): boolean => {
  return signInfoList.some(v => dayjs(v.signTime).format('yyyy/MM/dd') === day)
}

// 获取当前几天签到信息（包含今天）
export const getDistanceDays = (days: number, signInfoList: ISignInfoAggregate[]): signDayList[] => {
  let signDayList = []
  for (let index = 0; index < days; index++) {
    let signDay = formatDate(dayjs().subtract(index, 'day').valueOf()).format()
    const signInfo = signInfoList.find(v => v.signDay === signDay)
    signDayList.push({
      signDay,
      isSign: signInfo ? true : false
    })
  }
  return signDayList
}

// 获取几天前至今连续签到天数(包含今天)，如果昨天签到今天未签到，则也算连续签到，不算断签
export const getContinueDays = (days: number, signInfoList: ISignInfoAggregate[]): number => {
  const minYear = Math.min.apply(
    null,
    signInfoList.map(v => +v.y)
  )
  const list: number[] = signInfoList
    .map(v => {
      const gap = (isLeapYear ? 366 : 365) * (v.y - minYear)
      return gap + v.d
    })
    .sort((a, b) => a - b)

  if (list.length === 0) return 0
  let m = uniq(list.sort((a, b) => a - b))
  let max = 0
  //判断当天或者昨天是否已经签到
  const isSign = signInfoList.some(
    v => v.signDay === getToday() || v.signDay === formatDate(dayjs().subtract(-1, 'day').valueOf()).format()
  )
  for (let i = 0; i < days; i++) {
    if (isSign && m[i + 1] - m[i] === 1) {
      //当天或者昨天已经签到，则开始计算连续签到天数
      max++
    } else {
      break
    }
  }
  return max
}
